package net.oschina.app.viewpagerfragment.newsdetailfragment;

import android.view.View;
import android.widget.FrameLayout;

import net.oschina.app.MApp;
import net.oschina.app.R;

/**
 * Created by Ethan on 2017/4/6.
 */

public abstract class CommonFragment {
    public FrameLayout mRootView;
    public boolean isLoadData=false;//是否正在加载数据
    public boolean isReadData=false;//是否读取到数据
    public View mLoadingView;
    public View mErrorView;

    public CommonFragment(){
        mRootView = (FrameLayout)View.inflate(MApp.mContext, R.layout.common_fragment, null);
    }

    //展示加载中的界面
    public void showProgress(){
        if (mLoadingView==null) {
            mLoadingView = View.inflate(MApp.mContext, R.layout.view_loading_pager, null);
        }
        changeView(mLoadingView);
    }

    //展示加载失败页面
    public void showError(){
        if(mErrorView==null) {
            mErrorView = View.inflate(MApp.mContext, R.layout.view_error_pager, null);
        }
        changeView(mErrorView);
    }

    //切换界面
    public void changeView(View v) {
        if (mRootView!=null) {
            //在容器FrameLayout中先移除之前的view
            mRootView.removeAllViews();

            //添加加载中的view
            mRootView.addView(v);
        }
    }

    //确保跑在UI线程里面
    public void runOnUIThread(){
        MApp.mHandler.post(new Runnable() {
            @Override
            public void run() {
                isLoadData=true;
                if (isReadData){//加载到数据
                    showSuccess();
                }else {//加载数据失败
                    showError();
                }
            }
        });
    }

    //加载流程的启动
    public void dynamic(){
        //显示加载中的界面
        showProgress();
        //加载数据
        loadData();
    }

    //加载数据成功流程
    public void dealCommonSuccess(){
        //读取到数据
        isReadData=true;
        //将数据展示到UI
        runOnUIThread();
    }

    //加载数据失败的流程
    public void dealCommonFail(){
        isReadData=false;
    }

    //成功界面
    protected abstract void showSuccess();

    //加载数据
    protected abstract void loadData();
}
